<?php

/** libraries
 * http://docs.joomla.org/JToolBarHelper
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla view library
jimport('joomla.application.component.view');

class bgViewbg extends JView
{

    // Overwriting JView display method
    function display($tpl = null) {
        $user = JFactory::getUser();

        $model = $this->getModel();
        $this->model = $model;
        
        

        $model->_username = $user->username;

        $this->folders = $this->treeFolders($model->getFolders(), '|___ ');

        $cate = &JRequest::getVar('cate');
        $task = &JRequest::getVar('task');
        //echo 'cate '.$cate.', '.'task '.$task; 
        switch($task){
            case 'add':
                $this->setLayout('add');
            break;

            case 'upload':

            //echo file_get_contents('uploads/message/1391829357/B&G_既存コンパスマニュアル.jpg');
                JRequest::setVar('noHead', true);
                $this->mess = JRequest::getVar('jform');

                $attachment = $_FILES['Filedata'];

                $atts = array();
                // vong lap file dinh kem nguyen thuy
                foreach($attachment['tmp_name'] as $k=>$at){
                    if($at){
                        // kiem tra file csv chi dinh nguoi nhan
                        if($attachment['name'][$k] == 'recipients.csv'){
                            $recipients = $this->readCSV($at);
                        }else{
                            // upload file
                            $name = explode('.', $attachment['name'][$k]);
                            // giai nen neu la file zip va flag unzip la 1
                            if(end($name) == 'zip' && $this->mess['unzip'] == 1){
                                $zip = new ZipArchive(); 
                                $zip->open($at);

                                $folder = 'uploads/message/'.strtotime('now');
                                mkdir($folder, 0777);
                                $zip->extractTo($folder); 
                                $zip->close();

                                $this->reverseFolder($folder, &$recipients, &$atts);

                                //  //mb_internal_encoding("UTF-8");
                                // $files = scandir("$folder");
                                // foreach ($files as $filename) {
                                //     echo $filename.'<br/>';
                                //     if($filename == '.' || $filename == '..'){
                                //         continue;
                                //     }
                                //     $filename = iconv ( "SJIS" , "UTF-8", $filename );
                                //     //echo $filename.'<br/>';
                                //     $filename_short = end(explode('/', $filename));
                                //     if($filename_short == 'recipients.csv'){
                                //         $recipients = $this->readCSV($folder.'/'.$filename);
                                //     }else{
                                //         $name = explode('.', $filename_short);
                                //         //echo $filename_short;
                                //         $name = $name[0].'_'.strtotime('now').'.'.end($name);
                                //         //echo $name.'<br/>';
                                //         $encodeFile = sha1($name);

                                //         copy($folder.'/'.iconv ( "UTF-8", "SJIS" , $filename ), 'uploads/message/'.$encodeFile);
                                //         $atts[$name] = $filename_short; 
                                //     }
                                // }

                                // remove folder temp strototime
                                $this->delTree($folder);

                            }else{ // khong giai nen, upload len bthuong
                                $name = $name[0].'_'.strtotime('now').'.'.end($name);
                                $encodeFile = sha1($name);
                                move_uploaded_file($at, 'uploads/message/'.$encodeFile);

                                $atts[$name] = $attachment['name'][$k]; 
                            }
                            
                        }
                    }
                }    
               
                // chi dinh nguoi nhan voi tung file
                foreach($atts as $k => $v){
                    if(isset($recipients[$v])){
                        $atts[$k] = implode(',', $recipients[$v]);
                    }else{
                        $atts[$k] = null;
                    }
                }      

               
                // xử lý chuyển giá trị qua màn hình add
                $this->recipient = $this->mess['OCBA_CODE_LIST_SHOW'];
                $this->recipient_hidden = $this->mess['OCBA_CODE_LIST'];

                $this->TITLE = $this->mess['TITLE'];
                $this->BODY = $this->mess['BODY'];
                $this->ATTA_CODE_LIST = $this->mess['Filedata'];

                // $this->att = json_decode($this->ATTA_CODE_LIST);
                $this->att = $atts;

                $this->setLayout('add');
            break;

            case 'detail':
                $this->setLayout('detail');
            break;

            /*case 'folder':
                $this->setLayout('folder');
            break;
            */
            case 'reply':
            case 'forward':
                $id = JRequest::getVar('cid');
                //$id = $id[0];
                $this->tbl = JRequest::getVar('tbl');

                $this->mess = $model->getDetailMessage($id, $this->tbl, true );

                switch($this->tbl){
                    case 'mere' :

                        $this->recipient = $model->getUserByUsername($this->mess->MERE_USEM_CODE);
                        $this->recipient_hidden = $this->recipient.'('.$this->mess->MERE_USEM_CODE.')';

                        $this->TITLE = $this->mess->MERE_TITLE;
                        $this->BODY = $this->mess->MERE_BODY;
                        
                        $this->USEM_CODE = $this->mess->MERE_USEM_CODE;

                        // set body older
                        $this->DATE = $this->mess->MERE_DATE;
                        $this->from = $this->mess->MERE_USEM_CODE;
                        $this->to = $this->mess->MERE_OCBA_CODE;

                        // set attachment
                        $this->att = array();
                        $this->ATTA_CODE_LIST = $this->mess->MERE_ATTA_CODE_LIST;
                        $this->ATTA_CODE_LIST = explode('|', $this->ATTA_CODE_LIST);
                        foreach($this->ATTA_CODE_LIST as $att){
                            if($att){
                                $this->att[$att] = 'U_'.$this->USEM_CODE;
                            }
                        }
                    break;
                    case 'mese' :

                        $this->recipient = preg_replace("/\([^)]+\)/", null,$this->mess->MESE_OCBA_CODE);
                        $this->recipient_hidden = $this->mess->MESE_OCBA_CODE;

                        $this->TITLE = $this->mess->MESE_TITLE;
                        $this->BODY = $this->mess->MESE_BODY;
                        $this->ATTA_CODE_LIST = $this->mess->MESE_ATTA_CODE_LIST;

                         // set body older
                        $this->from = $this->mess->MESE_USEM_CODE;
                        $this->DATE = $this->mess->MESE_DATE;
                        $this->to = $this->mess->MESE_OCBA_CODE;

                        // set attachment
                        $this->att = json_decode($this->ATTA_CODE_LIST);
                    break;
                }

                // if message is forward, recipient set to null
                if($task == 'forward'){
                    $this->recipient = '';
                    $this->recipient_hidden = '';
                }

                $body = $this->BODY;
                $this->BODY = "\r\n\r\n-----Original Message-----";
                $this->BODY .= "\r\nFrom : ".$model->getUserByUsername($this->from);

                $this->to = !strpos($this->to, ';') ? $model->getUserByUsername($this->to) : preg_replace("/\([^)]+\)/", null,$this->to);
                $this->BODY .= "\r\nTo : ".$this->to;
                $this->BODY .= "\r\nDate : ".$this->DATE;
                $this->BODY .= "\r\n\r\n".$body;

                if($task == 'reply'){
                    $this->att = null;
                }

                $this->setLayout('add');

                // set display template

            break;

             /*** CASE VIEW **/
            case 'view':

                $id= JRequest::getVar('cid');
                switch($cate){
                    case 'inbox':
                        $this->mess = $model->getDetailMessage($id, 'mere');
                        $model->setChecked($id);

                        $this->mess->MERE_USEM_CODE = $model->getUserByUsername($this->mess->MERE_USEM_CODE);
                        $this->mess->MERE_OCBA_CODE_LIST = preg_replace("/\([^)]+\)/", null,$this->mess->MERE_OCBA_CODE_LIST);

                        $this->folder = '受信トレイ';

                        $this->setLayout('view');
                    break;

                    case 'sent':
                        $this->mess = $model->getDetailMessage($id, 'mese');
                        $this->folder = '送信済み';

                        $this->unRead = $model->getUnread($id);
                        $this->unRead = $model->getUserByArrayUsername($this->unRead);
                        $this->unRead = array_merge(array('未読リスト'), $this->unRead);

                        $this->mess->MESE_USEM_CODE = $model->getUserByUsername($this->mess->MESE_USEM_CODE);
                        $this->mess->MESE_OCBA_CODE = preg_replace("/\([^)]+\)/", null,$this->mess->MESE_OCBA_CODE);

                        $this->setLayout('view_sent');

                    break;

                    case 'draft':

                        JRequest::setVar('noHead', true);
                        // controller xử lý chuyển đến trang edit rồi
                        $this->mess = $model->getDetailMessage($id, 'mese');

                        $this->recipient = preg_replace("/\([^)]+\)/", null,$this->mess->MESE_OCBA_CODE);
                        $this->recipient_hidden = $this->mess->MESE_OCBA_CODE;

                        $this->TITLE = $this->mess->MESE_TITLE;
                        $this->BODY = $this->mess->MESE_BODY;
                        $this->ATTA_CODE_LIST = $this->mess->MESE_ATTA_CODE_LIST;

                        $this->att = json_decode($this->ATTA_CODE_LIST);

                        $this->setLayout('add');
                    break;

                    case 'trash':
                        $tbl = JRequest::getVar('tbl');
                        $this->mess = $model->getDetailMessage($id, $tbl, true);

                        $this->folder = '下書き ';

                        if($tbl == 'mese'){

                            $this->mess->MESE_USEM_CODE = $model->getUserByUsername($this->mess->MESE_USEM_CODE);
                            $this->mess->MESE_OCBA_CODE = preg_replace("/\([^)]+\)/", null,$this->mess->MESE_OCBA_CODE);

                            $this->unRead = $model->getUnread($id);
                            $this->unRead = $model->getUserByArrayUsername($this->unRead);
                            $this->unRead = array_merge(array('未読リスト'), $this->unRead);

                            $this->setLayout('view_sent');
                        }else{
                            $this->mess->MERE_USEM_CODE = $model->getUserByUsername($this->mess->MERE_USEM_CODE);
                            $this->mess->MERE_OCBA_CODE_LIST = preg_replace("/\([^)]+\)/", null,$this->mess->MERE_OCBA_CODE_LIST);
                            $this->setLayout('view');
                            $model->setChecked($id);
                        }

                    break;

                    case 'search':
                        $this->folder = '検索';
                    case 'folder':
                        $tbl = JRequest::getVar('tbl');
                        $this->mess = $model->getDetailMessage($id, $tbl, true);

                        if(!$this->folder){
                            $this->folder = $this->mess->FOME_NAME;
                        }

                        if($tbl == 'mese'){
                            $this->mess->MESE_USEM_CODE = $model->getUserByUsername($this->mess->MESE_USEM_CODE);
                            $this->mess->MESE_OCBA_CODE = preg_replace("/\([^)]+\)/", null,$this->mess->MESE_OCBA_CODE);

                            $this->unRead = $model->getUnread($id);
                            $this->unRead = $model->getUserByArrayUsername($this->unRead);
                            $this->unRead = array_merge(array('未読リスト'), $this->unRead);
                            $this->setLayout('view_sent');
                        }else{
                            $this->mess->MERE_USEM_CODE = $model->getUserByUsername($this->mess->MERE_USEM_CODE);
                            $this->mess->MERE_OCBA_CODE_LIST = preg_replace("/\([^)]+\)/", null,$this->mess->MERE_OCBA_CODE_LIST);

                            $this->setLayout('view');
                            $model->setChecked($id);
                        }

                    break;

                } // end switch cate


                $this->folders = array_merge(array(0=>'移動'), $this->folders);
            break;
            /*** END CASE VIEW **/

            /*** SEARCH */
            case 'search':

                $this->title = '検索';
                $this->search();
            break;

            /*** END SEARCH */

            /*** LIST **/
            default : // no task

                $titleSearch = JRequest::getVar('title_search', null);

                switch($cate){
                    /* table mese */
                    case 'sent':
                        $this->inbox = $model->getSent($titleSearch);
                        $this->tbl = 'F';

                        $this->titleRESE = '送信先';
                        $this->title = '送信済み';
                        $this->RESE = 'F_OCBA_CODE';
                        //$this->inbox->F_OCBA_CODE = preg_replace("([.*])", null, $this->inbox->F_OCBA_CODE);
                    break;

                    case 'draft':
                        $this->inbox = $model->getDraft($titleSearch);

                        $this->tbl = 'F';

                        $this->titleRESE = '送信先';
                        $this->title = '下書き';
                        $this->RESE = 'F_OCBA_CODE';
                    break;

                    /* table mere */
                    case 'trash':
                        $this->inbox = $model->getTrash($titleSearch);

                        $this->tbl = strtoupper($this->getTable());

                        $this->titleRESE = '送信者';
                        $this->title = 'ゴミ箱';
                        $this->RESE = 'F_USEM_CODE';
                    break;

                    case 'inbox':
                        $this->inbox = $model->getInbox($titleSearch);
                        $this->tbl = 'F';
                        //$this->tbl = strtoupper($this->getTable());

                        $this->titleRESE = '送信者';
                        $this->title = '受信トレイ';
                        $this->RESE = 'name';
                    break;

                    case 'folder':
                        $idFolder = JRequest::getVar('id',0);

                        $this->inbox = $model->getFolder($idFolder,$titleSearch);

                        $this->tbl = strtoupper($this->getTable());

                        $this->titleRESE = '送信者';
                        $this->title = '個人用フォルダ';
                        //$this->RESE = 'name';
                        $this->RESE = 'F_USEM_CODE';

                        // chu y de sau dong code $this->tbl

                    break;

                    case 'search':
                        $this->search();
                    break;

                } // end switch cate

                //$this->setLayout('default');

        } // edn switch task

        $this->pagination =& $this->get('Pagination');
        parent::display();
    }

    public function getTable(){
    $cate = JRequest::getVar('cate');
        switch($cate){
            case 'trash':
                return 'F';
            break;

            case 'inbox':
                return 'mere';
            break;
            case 'draft':
            case 'sent':
                return 'mese';
            break;
            case 'folder':
                return 'F';
            break;

        }
    }


    public function search(){
        $user = JFactory::getUser();

        $filter = JRequest::getVar('jsearch');

        switch($filter['folder']){
            case 'inbox':
                $this->inbox = $this->model->getSearchInbox($filter);
                $this->setLayout('searchinbox');
            break;

            case 'sent':
                $this->inbox = $this->model->getSearchSent($filter);
                $this->setLayout('searchsent');
            break;

            case 'trash':
                $this->inbox = $this->model->getSearchTrash($filter);
                $this->setLayout('searchtrash');
            break;

            case 'all':
            
                $this->inbox = $this->model->getSearchAll($filter);
                $this->setLayout('searchall');
            break;

            default:
                $this->inbox = $this->model->getSearchFolder($filter);
                $this->setLayout('searchfolder');
            break;
        }

        $_SERVER['QUERY_STRING'] = "top=page&option=com_frmessage&cate=search";
        JRequest::setVar('cate', 'search');
    }

    public function treeFolders($folders, $stringPrefix = '|_ '){
        if(!$folders){
            return array();
        }
        $listFolder = array();
        foreach($folders as $fol){
            $listFolder[$fol->FOME_PARENT][] = $fol;
        }

        $folders = array();
        foreach($listFolder[0] as $fol){
            $folders[] = $fol;
            if($listFolder[$fol->FOME_CODE]){
                foreach($listFolder[$fol->FOME_CODE] as $f){
                    $f->FOME_NAME = $stringPrefix.$f->FOME_NAME;
                    $folders[] = $f;
                }
            }

        }

        return $folders;
    }

    function readCSV($file){
        ini_set('auto_detect_line_endings',TRUE); //Check keyword /n or /r in MAC OS and WINDOWS, LINUX
        if (fopen($file, 'r')) {
            $file_handle = fopen($file, 'r');
            setlocale(LC_ALL, 'Ja_JP.Shift_JIS');
            while (!feof($file_handle)) {
                $line = fgetcsv($file_handle, 1024);
                //$line_of_text[] = fgetcsv($file_handle, 1024,',');
                if(count($line) > 1){
                    $line_of_text[] = $line;
                }else{
                    $line = explode(';', $line[0]);
                    $line_of_text[] = $line;
               }
            }
            $data = "";
            foreach ($line_of_text as $key => $value) {
                if (count($value) == 1) {
                    unset($line_of_text[$key]);
                    continue;
                }
                foreach($value as $k=>$v){
                    $data[$key][$k] = iconv ("SJIS", "UTF-8" , $v ); //SJIS => UTF-8 before insert Database
                }
            }
            
            // dong ket noi doc file
            fclose($file_handle);
            
            // xu ly mang sau khi da doc
            array_shift($data);
            
            $list = array();
            foreach($data as $row){
                $list[$row[2]][] = $row[0].'_'.$row[1];
            }

            return $list;            
        }
    }

    // xoa cây thư mục
    function delTree($dir){ 
        $files = array_diff(scandir($dir), array('.','..')); 

        foreach ($files as $file) { 
            (is_dir("$dir/$file")) ? $this->delTree("$dir/$file") : unlink("$dir/$file"); 
        }

        return rmdir($dir); 
    } 

    function reverseFolder($folder, $recipients, $atts){
        
        //mb_internal_encoding("UTF-8");
        $files = glob("$folder/*");
        foreach ($files as $filename) {
            // neu la folder thi duyet qua folder, de quy
            if(is_dir($filename)){
                $this->reverseFolder($filename, &$recipients, &$atts);
                continue;
            }

            $filename = iconv ( "SJIS" , "UTF-8", $filename );
            //echo $filename.'<br/>';
            $filename_short = end(explode('/', $filename));
            if($filename_short == 'recipients.csv'){
                $recipients = $this->readCSV(iconv ( "UTF-8", "SJIS" , $filename ));
            }else{
                $name = explode('.', $filename_short);
                //echo $filename_short;
                $name = $name[0].'_'.strtotime('now').'.'.end($name);
                //echo $name.'<br/>';
                $encodeFile = sha1($name);

                copy(iconv ( "UTF-8", "SJIS" , $filename ), 'uploads/message/'.$encodeFile);
                $atts[$name] = $filename_short; 
            }
        }
    }

}


